package routers

import (
	"fmt"
	"github.com/gin-contrib/sessions"
	"github.com/gin-contrib/sessions/redis"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/validator/v10"
	"giv-vue-blog/api"
	"giv-vue-blog/global"
	"giv-vue-blog/middleware"
	"giv-vue-blog/utils/validators"
)

// TODO: 方法一 使用cookie当做存储引擎 基于 Cookie 存储 Session Sessions: 认证通过后需要将用户的session数据保存在内存中，随着认证用户的增加，内存开销会大
// var store = cookie.NewStore([]byte("xwen24652sdfn1"))
// TODO: 方法二 使用redis当做存储引擎 基于 redis存储
/* 初始化基于redis的存储引擎: 需要启动redis服务,不然会报错
参数说明:
自第1个参数-redis最大的空闲连接数
第2个参数-数通信协议tcp或者udp
第3个参数-redis地址,格式，host:port
第4个参数-redis密码
第5个参数-session加密密钥
*/
var store, _ = redis.NewStore(10, "tcp", "127.0.0.1:6379", "1234", []byte("Swen24652sdn1"))

func (router RouterGroup) UserRouter() {
	userApi := api.ApiGroupApp.UserApi
	// TODO: 注册自定义验证器函数
	if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
		v.RegisterValidation("user_name", validators.ValidateName)
		v.RegisterValidation("password", validators.ValidatePassword)
		v.RegisterValidation("RoleValidator", validators.RoleValidate)
		v.RegisterValidation("SignStatusValidator", validators.SignStatusValidate)
		v.RegisterValidation("TelValidator", validators.TelValidate)
	}
	// TODO: 设置session中间件，参数sessionId，指的是session的名字，也是cookie/REdis的名字
	router.Use(sessions.Sessions("sessionId", store))
	//TODO :路由
	router.POST("email_login", userApi.EmailLoginView)
	router.POST("logout", middleware.JwtAuth(), userApi.LogoutView)
	router.GET("user_list", middleware.JwtAdmin(), userApi.UserListView)
	router.PUT("user_role", middleware.JwtAdmin(), userApi.UserUpdateRole)
	router.PUT("user_pwd", middleware.JwtAuth(), userApi.UserUpdatePwdView)
	router.DELETE("user", middleware.JwtAdmin(), userApi.UserDelView)
	router.POST("user_bind_email", middleware.JwtAuth(), userApi.UserBindEmail)
	router.POST("user_create", middleware.JwtAdmin(), userApi.CreateUserView)
	fmt.Printf("%s:%d", global.Config.Redis.IP, global.Config.Redis.Port)

}
